Skip to content

Fix memory leak in shutdown handler using WeakReference#539

Open
JanTvrdik wants to merge 2 commits intoKnpLabs:masterfrom
JanTvrdik:fix/memory-leak-shutdown-handler
Open

Fix memory leak in shutdown handler using WeakReference#539
JanTvrdik wants to merge 2 commits intoKnpLabs:masterfrom
JanTvrdik:fix/memory-leak-shutdown-handler

Conversation

@JanTvrdik
Copy link

Summary

  • Fix memory leak caused by register_shutdown_function holding a strong reference to $this
  • Use WeakReference to allow normal garbage collection while still cleaning up temporary files at shutdown

Problem

The shutdown handler was registered with [$this, 'removeTemporaryFiles'], which kept a strong reference to the generator object. This prevented garbage collection until script termination, causing memory leaks in long-running processes or when creating many generator instances.

Solution

Wrap $this in a WeakReference so the object can be garbage collected normally. The shutdown handler checks if the object still exists before calling removeTemporaryFiles().

Test plan

  • Existing tests should pass
  • Memory usage should no longer grow unboundedly when creating multiple generator instances

The register_shutdown_function was holding a strong reference to $this,
preventing garbage collection until script termination. This change wraps
the reference in a WeakReference, allowing normal garbage collection while
still cleaning up temporary files at shutdown if the object still exists.
Copilot AI review requested due to automatic review settings January 27, 2026 11:58
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a memory leak in long-running PHP processes by preventing the shutdown handler from holding a strong reference to generator instances. By using WeakReference, the generator objects can be garbage collected normally while still ensuring temporary files are cleaned up during abnormal script termination.

Changes:

  • Replaced direct object reference in shutdown handler with WeakReference to allow garbage collection
  • Used null-safe operator to safely call removeTemporaryFiles() only if the object still exists at shutdown

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants